package cn.xxstudy.visitshop.ui.activity.main.fragment.visit

import android.content.Intent
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.xxstudy.visitshop.R
import cn.xxstudy.visitshop.adapter.VisitAdapter
import cn.xxstudy.visitshop.base.adapter.OnItemClickListener
import cn.xxstudy.visitshop.base.fragment.LazyFragment
import cn.xxstudy.visitshop.util.configAppearance
import cn.xxstudy.visitshop.ui.activity.main.fragment.visit.model.VisitData
import cn.xxstudy.visitshop.ui.activity.main.fragment.visit.viewmodel.VisitViewModel
import cn.xxstudy.visitshop.ui.activity.visit.VisitDetailActivity
import cn.xxstudy.visitshop.util.VISIT_KEY
import kotlinx.android.synthetic.main.fragment_visit.*
import kotlinx.android.synthetic.main.include_toolbar.*

/**
 * @author ：DELL on 2021/3/23 .
 * @packages cn.xxstudy.visitshop.ui.activity.main.fragment.visit
 * @TODO: 巡店
 */
class VisitFragment : LazyFragment(), Toolbar.OnMenuItemClickListener,
    SwipeRefreshLayout.OnRefreshListener, OnItemClickListener<VisitData> {

    private lateinit var viewModel: VisitViewModel
    override val layoutId = R.layout.fragment_visit

    override fun initView() {
        toolbarTitle.text = "巡店"
        toolBar.inflateMenu(R.menu.menu_visit)
        toolBar.setOnMenuItemClickListener(this)
        visitRefresh.setOnRefreshListener(this)
        visitRefresh.configAppearance()
        visitContent.configAppearance(context)
    }

    override fun loadData() {
        viewModel = ViewModelProvider(this).get(VisitViewModel::class.java)
        val adapter = VisitAdapter()
        adapter.setOnItemClickListener(this)
        visitContent.adapter = adapter
        viewModel.visitLiveData.observe(viewLifecycleOwner, Observer {
            adapter.datas = it
            visitRefresh.isRefreshing = false
        })

        viewModel.failLiveData.observe(viewLifecycleOwner, Observer {
            visitRefresh.isRefreshing = false
        })

        visitRefresh.post {
            visitRefresh.isRefreshing = true
            viewModel.visit("0001")
        }

    }

    override fun onMenuItemClick(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.visitAdd -> Toast.makeText(context, "Add", Toast.LENGTH_SHORT).show()
            R.id.visitSearch -> Toast.makeText(context, "Search", Toast.LENGTH_SHORT).show()
        }
        return true
    }

    override fun onRefresh() {
        viewModel.visit("0001")
    }

    override fun onClickItem(position: Int, data: VisitData) {
        val intent = Intent(activity, VisitDetailActivity::class.java)
        intent.putExtra(VISIT_KEY, data)
        startActivity(intent)
    }
}